/////////////////////////////////////////////
/// Implementation of the who needs a xoperator
/////////////////////////////////////////////

context.startComposing();
query = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+ 
		"SELECT ?name ?f ?lastname ?s ?label ?z"+ 
		"WHERE { ?s foaf:knows ?z. " + 
		"OPTIONAL {?s foaf:name ?name}. OPTIONAL {?s foaf:surname ?lastname}. OPTIONAL {?s foaf:firstName ?firstname} . OPTIONAL {?s rdfs:label ?label}}"
context.log.info(query);
found = false;
error ="";
def countmap = [:]; 		
context.queryForTable(query,true,[],null).each{res->
	if(res.errors==null||res.errors.empty){
			res.resultRows.each{row->
				user = ""
				if(row["name"]!=null){
					user = row["name"]
				}else{
					if(row["firstname"] !=null){ 
						user = row["firstname"]
					} 
					if(row["lastname"] !=null){
					user += row["lastname"]
					}
				}
				if(user.empty && row["label"]!=null){
					user = row["label"]
				}
				
				if(user.empty){
					user = row["s"];
				}
				if(countmap[row["s"]]==null){
					def ex = new Expando();
					ex.count = 1;
					ex.name =  user; 
					countmap[row["s"]] = ex;
				}else{
					
					countmap[row["s"]].count = countmap[row["s"]].count +1;
					//context.log.info("incremented");
				}
				
				//context.sendMessageToUser(user + "(by store: " + res.storeName + "), " )
				found = true;
				}

	}else{
		error += " " + res.storeName +": " + res.errors
	}
	
}
def resMap = new TreeMap();

countmap.each{key,value->
	resMap.put(value.count,value.name.trim());
	//context.sendMessageToUser(value.name +  " hotness is:  " + value.count);
}

resMap.each(){value,key->
	context.sendMessageToUser(key +  " hotness is:  " + value);
}




if(!found){
		context.sendMessageToUser("Nobody");
}

if(!error.empty){
	context.sendMessageToUser("Some error occured: " + error);
}
